package com.shujia.mysql;

import java.sql.*;

/**
 * @Description: MySQLJDBC5 java操作事物
 * @Author: 王火火
 * @Date: 2019/9/6 15:11
 */
public class MySQLJDBC5 {
    //创建常量
    static final String DRIVER = "com.mysql.jdbc.Driver";//驱动
    static final String URL = "jdbc:mysql://master:3306/shujia";//路劲
    static final String USERNAME = "root";//用户名
    static final String PASSWORD = "123456";//密码

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;
        //加载驱动
        try {
            Class.forName(DRIVER);
            //获取连接
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            conn.setAutoCommit(false);//修改自动提交事物
        } catch (Exception e) {
            e.printStackTrace();
        }
        try{
            //第一个添加
            String sql1 = "insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) " +
                    "values(12,'test','job',5000,'1999-03-03',5000,100,20)";
            //获取执行器
            ps1 = conn.prepareStatement(sql1);
            int i1 = ps1.executeUpdate();

            //第二个添加
            String sql2 = "insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) " +
                    "values(13,'test','job',5000,'1999-03-03',5000,100,20)";
            ps2 = conn.prepareStatement(sql2);
            int i2 = ps2.executeUpdate();
            conn.commit();
        }catch (Exception e){
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        try{
            ps2.close();
            ps1.close();
            conn.close();
        }catch (Exception e){
            System.out.println("连接关闭");
        }
    }
}
